package com.jweb.framework.http.interceptors;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;

import com.jweb.framework.core.ContextEx;
import com.jweb.framework.core.CoreRuntimeException;
import com.jweb.framework.core.channel.ChannelContext;
import com.jweb.framework.core.support.TRACER;
import com.jweb.framework.http.ContentLengthResolver;
import com.jweb.framework.http.support.MimeTypes;
import com.jweb.framework.http.support.Utils;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：接收流拦截器
 */
public class JsonStreamPayloadChannelInterceptor implements ServletChannelInterceptor {
	
	private final MimeTypes mimeTypes = new MimeTypes();
	private String contentType ;
	private String encoding = "UTF-8";
	
	private boolean extractIdentityFromURI ;
	
	private HttpStreamResolver streamResolver = new ContentLengthResolver();
	
	public void setContentType(String contentType){
		this.contentType = contentType ;
	}
	
	public void setEncoding(String encoding){
		this.encoding = encoding ;
	}
	
	public void setExtractIdentityFromURI(boolean eif){
		this.extractIdentityFromURI = eif ;
	}
	
	public void setStreamResolver(HttpStreamResolver hsr){
		this.streamResolver = hsr ;
	}
	
	public void onRequest(ChannelContext channelContext , ContextEx contextEx) throws CoreRuntimeException {
		
		HttpServletRequest request = (HttpServletRequest) channelContext.getRequest();
		//request.getInputStream().available()
		if(this.extractIdentityFromURI){
			String str = Utils.getIdentity(request);
			contextEx.setProcessId(str);
		}
		
		channelContext.setRequestPayload(this.streamResolver.resolve(request)) ;
		
	}
	
	public void onResponse(ChannelContext channelContext , ContextEx contextEx , Throwable throwable) {
		
		String str = contextEx.getData("X-processType");
		if(str!=null && str.equals("X-Download")){
			return ;
		}
		
		byte[] bytes = (byte[]) channelContext.getResponsePalyload();
		try {
			
			HttpServletResponse response = (HttpServletResponse) channelContext.getResponse() ;
			if(this.contentType != null){
				response.setContentType(this.contentType);
			}
			else {
				List list = this.mimeTypes.getMediaTypes((HttpServletRequest) channelContext.getRequest());
				
				if(!list.isEmpty()){
					response.setContentType(MediaType.toString(list));
				}
			}
			
			response.setContentLength(bytes.length);
			response.setLocale(contextEx.getLocale());
			if(this.encoding != null){
				response.setCharacterEncoding(this.encoding);
			}
			response.getOutputStream().write(bytes);
			response.getOutputStream().flush();
			
		} catch (IOException e) {
			TRACER.trace("write http stream error ." , e);
		}
		
		
	}
	
}
